<?php
declare (strict_types = 1);

namespace app\api\controller\v1;

use app\api\helpers\v1\traits\SearchDataForModel;
use app\api\model\v1\AdminLog;
use app\api\model\v1\ProjectSample;
use app\api\validate\v1\SamValidate;
use app\BaseController;
use think\exception\ValidateException;
use think\Request;

class ProjectSampleCon extends BaseController
{
    use SearchDataForModel;

    /**
     * @User: 刘海龙
     * @Date: 2021/11/16
     * @Time: 13:52
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * 样本点数据源列表
     */
    public function getProjectSampleList(){
        $limit = $this->request->param('limit',10);
        $res = $this->search(new ProjectSample(),[],$limit,'desc',['projectType']);
        return $this->response($res);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/11/16
     * @Time: 15:14
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 编辑and新增
     */
    public function saveProjectSample(){
        $id = $this->request->param('id', 0);
        $data = $this->request->param();
        try {
            $validator = $this->validate($this->request->param(),
                SamValidate::rules($id),
                SamValidate::msg());
            if ($validator){
                if (intval($id) === 0) {
                    ProjectSample::create($data);
                } else {
                    $sam = ProjectSample::find($id);
                    $sam->update($data);

                }
                AdminLog::record(intval($id) === 0 ? '新增项目样本点' : '编辑项目样本点', $this->request->param(), $this->request->uid, $this->request->username);
                return $this->response();
            }
        }catch (ValidateException $exception){
            return $this->response(403,$exception->getError());
        }
    }

    /**
     * @param $id
     * @User: 刘海龙
     * @Date: 2021/11/16
     * @Time: 15:22
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 删除项目样本点
     */
    public function delProjectSample($id){
        $ids = explode(',', $id);
        foreach ($ids as $id) {
            $sample = ProjectSample::find(intval($id));
            if (is_null($sample)) {
                return $this->response(404, '此样本不存在');
            }
            $sample->force()->delete();
            AdminLog::record('删除单位', $this->request->param(), $this->request->uid, $this->request->username);
        }
        return $this->response();
    }
}
